<template>
  <el-upload
    class="avatar-uploader"
    :action="uploadUrl"
    :before-upload="beforeUpload"
    :on-change="handleChange"
    :file-list="fileList"
    drag
    accept="image/jpeg,image/png"
    :auto-upload="false"
    ref="upload"
  >
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
  </el-upload>
</template>

<script>
import { preprocessImage } from '@/views/demo/page1/utils/formatImages'

export default {
  data () {
    return {
      imageUrl: '', // 用于存储上传图片的 URL，用于回显
      fileList: [], // 用于存储上传的文件列表
      uploadUrl: 'xxx' // 请替换为你的上传接口
    }
  },
  methods: {
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式！')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB！')
        return false
      }
      return true
    },
    handleChange (file, fileList) {
      this.fileList = fileList.slice(-1) // 限制最多只能上传一张图片
      if (fileList.length > 0) {
        this.imageUrl = URL.createObjectURL(file.raw) // 回显图片
        this.$emit('change', this.imageUrl)
      }
    },

    submitUpload () {
      if (this.fileList.length === 0) {
        this.$message.warning('请先选择一张图片！')
        return
      }
      this.$refs.upload.submit() // 手动触发上传
    }
  }
}
</script>

<style scoped>

</style>
